<?php
class UsersBatch extends AppModel {
	var $name = 'UsersBatch';
	
	var $validate = array(
		'user_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'batch_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);
	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $belongsTo = array(
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'user_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Batch' => array(
			'className' => 'Batch',
			'foreignKey' => 'batch_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);
    
    function getBatch($user_id)
    {
        return $this->find('first',array('conditions'=>array('UsersBatch.user_id'=>$user_id),'order'=>'UsersBatch.id desc'));
    }
    
    function getAndAssignBatch($user_id)
    {
        if($batch = $this->getBatch($user_id)){
            return $batch;
        }
        else{
            return $this->assignBatch($user_id);
        }
    }
    
    function assignBatch($user_id)
    {
        App::import('Model','Batch');
        $batchModel = new Batch();
        //get random batch        
        if($batch = $batchModel->getRandom()){
            $data = array();
            $data['batch_id'] = $batch['Batch']['id'];
            $data['user_id'] = $user_id;
            $data['session1_start_time'] = date('Y-m-d H:i:s');
            $this->create();
            $this->save($data);
            $data = $this->read(null,$this->id);
            return $data;            
        }        
        return false;
    }
    
    function isValidSession($batch,$limit_1=75,$limit_2=15)
    {
        //debug($batch);
        $diff_1 = $this->diff($batch['UsersBatch']['session1_start_time']);
        
        if($batch['UsersBatch']['session2_start_time'] != '0000-00-00 00:00:00') $diff_2 = $this->diff($batch['UsersBatch']['session2_start_time']);        
        if($diff_1<($limit_1*60) && $batch['UsersBatch']['session1_end_time'] == '0000-00-00 00:00:00')
        {            
            return array('diff_1'=>(($limit_1*60)-$diff_1));
        }
        elseif($batch['UsersBatch']['session2_start_time'] != '0000-00-00 00:00:00' && $diff_2<($limit_2*60))
        {
            //set session 1 end time
            $this->updateSession1Completed($batch['UsersBatch']['user_id'],$batch['UsersBatch']['batch_id']);            
            return array('diff_2'=>(($limit_2*60)-$diff_2));
        }
        else {
            $this->setCompleted($batch['UsersBatch']['user_id'],$batch['UsersBatch']['batch_id']);  
            return false;  
        }        
        return false;
    }
    
    function updateSession1Completed($userId,$batchId)
    {
        return $this->updateAll(array('UsersBatch.session1_end_time'=>'"'.date('Y-m-d H:i:s').'"'),array('UsersBatch.user_id'=>$userId,'UsersBatch.batch_id'=>$batchId, 'UsersBatch.session1_end_time'=>null));        
    }

    
    function endSession1AndSetCompleted($userId,$batchId)
    {
        $this->recursive = -1;
        return $this->updateAll(array('UsersBatch.status'=>'\'completed\'','UsersBatch.session1_end_time'=>'"'.date('Y-m-d H:i:s').'"'),array('UsersBatch.user_id'=>$userId,'UsersBatch.batch_id'=>$batchId));
    }
    
    function endSession2AndSetCompleted($userId,$batchId)
    {
		App::import('Model','User');        
		$userModel = new User();
		$userModel->recursive = -1;
		//make user status 
		$userModel->updateAll(array('User.test_status'=>"'waiting'"),array('User.id'=>$userId));
		
        $this->recursive = -1;		
        return $this->updateAll(array('UsersBatch.status'=>'\'completed\'','UsersBatch.session2_end_time'=>'"'.date('Y-m-d H:i:s').'"'),array('UsersBatch.user_id'=>$userId,'UsersBatch.batch_id'=>$batchId));
    }
    
    function setCurrentPartId($batch,$part_id)
    {
        $this->updateAll(array('UsersBatch.current_part_id'=>$part_id),array('UsersBatch.user_id'=>$batch['UsersBatch']['user_id'],'UsersBatch.batch_id'=>$batch['UsersBatch']['batch_id']));
    }
    
    function startSession2($userId,$batchId)
    {
        return $this->updateAll(array('UsersBatch.session2_start_time'=>'"'.date('Y-m-d H:i:s').'"'),array('UsersBatch.user_id'=>$userId,'UsersBatch.batch_id'=>$batchId));
    }

    function setCompleted($userId,$batchId,$userStatus='failed')
    {
		App::import('Model','User');        
		$userModel = new User();
		$userModel->recursive = -1;
		//make user status 
		$userModel->updateAll(array('User.test_status'=>"'".$userStatus."'"),array('User.id'=>$userId));
		
        $this->recursive = -1;
        return $this->updateAll(array('UsersBatch.status'=>'\'completed\''),array('UsersBatch.user_id'=>$userId,'UsersBatch.batch_id'=>$batchId));
    }
    
    function isNotExpired($time,$limit=75)
    {
        $diff_1 = $this->diff($time);
        if($diff_1<($limit*60)) return true;
        return false;
    }
}
